<template>
  <div class="timeAxisWrap" :style="timeAxisStyle">
    <div class="control_items">
      <div class="time_case">{{ currentTime }}
      </div>
      <div class="btns">
        <el-tooltip effect="light" content="向后" popper-class="el_tooltip" placement="top" :offset="10">
          <button class="pre_btn" @click="preHandle" :disabled="controlsDisabled">
            <svg-icon name="wmc-pre" style="
                width:20px;
                height:20px;
                color: #ffffff;
              " />
          </button>
        </el-tooltip>

        <el-tooltip effect="light" :content="store.$state.curIsPlay
          ? `${controlBtn.suspendContent}`
          : `${controlBtn.playContent}`
          " popper-class="el_tooltip" placement="top" :offset="10">
          <button class="play_btn" @click="playHandle" :disabled="controlsDisabled">
            <svg-icon :name="store.$state.curIsPlay ? 'wmc-pause' : 'wmc-play'" style="
                width:20px;
                height:20px;
                margin-top: 2px;
                color: #ffffff;
              " />
          </button>
        </el-tooltip>
        <el-tooltip effect="light" content="向前" popper-class="el_tooltip" placement="top" :offset="10">
          <button class="next_btn" @click="nextHandle" :disabled="controlsDisabled">
            <svg-icon name="wmc-next" style="
                width:20px;
                height:20px;
                margin-top: 2px;
                color: #ffffff;
              " />
          </button>
        </el-tooltip>
      </div>
      <div class="time_interval">
        <span class="time_interval_title">倍速</span>
        <el-select v-model="store.$state.timeIntervalValue" @change="changeStepHandle" size="small" :disabled="controlsDisabled">
          <el-option v-for="item in store.$state.timentervalOptions" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </div>
    </div>
    <div class="axis">
      <el-slider v-model="satelliteValue" :show-tooltip="false" :min="0" :max="maxValue" :marks="marks"
        @change="onSliderChange" :disabled="controlsDisabled"></el-slider>
      <div class="absolute top-0px nowTime" :style="{ left: `${progressPosition}%` }">
        {{ nowTime }}
      </div>
    </div>
  </div>
</template>

<script setup>
/**  
* @description 时间轴组件
* @param timentervalOptions 倍速选项
* @param startTime 开始时间（秒）
* @param endTime 结束时间（秒）
* @param interval 每大刻度间隔
* @param smallInterval 每个大刻度之间的小刻度数
* @methods timeChange 取到当前进度方法  
*/
import { ref, reactive, onMounted, nextTick, watch, watchEffect, computed, toRefs } from 'vue'
import { useRoute } from 'vue-router'
import moment from 'moment'
// import settings from "@/settings.ts";
import mapStore from "@/stores/modules/map.ts";
const store = mapStore()
const route = useRoute();

// 添加计算属性判断控件是否可用
const controlsDisabled = computed(() => {
  if (store.startTime) {
    return false
  }
  return true
})

const timeAxisStyle = computed(() => {
  let fullScreenMenu = ['/home/index']
  let width = '100%'
  
  // if (!fullScreenMenu.includes(route.path)) {
  //   width = `calc(100vw - ${globalStore.isCollapse ? settings.asideMenuCollapseWidth : globalStore.menuWidth + 'px'})`
  // }

  return { width }
})

const controlBtn = reactive({
  playContent: '播放',
  suspendContent: '暂停'
})
watch(() => store.$state.curIsPlay, (newVal) => {
  if (!newVal) {
    clearInterval(timer)
  }
})
const satelliteValue = ref(0)
let timer = null
// 进度播放
const playHandle = (type = 'nextHandle') => {
  store.setCurIsPlay(!store.$state.curIsPlay)
  if (store.$state.curIsPlay) {
    timer = setInterval(() => {
      satelliteValue.value = type !== 'preHandle' ? satelliteValue.value + 1 : satelliteValue.value - 1
    }, (1000 / store.$state.timeIntervalValue))
  } else {
    clearInterval(timer)
  }
}
// 向后
const preHandle = () => {
  satelliteValue.value -= 1
}
// 向前
const nextHandle = () => {
  satelliteValue.value += 1
}
// 倍速
const changeStepHandle = (val) => {
  playHandle()
}
// 滑动条改变
const progressPosition = computed(() => {
  return (satelliteValue.value / maxValue.value) * 100
})



const nowTime = computed(() => {
  const seconds = satelliteValue.value + store.$state.startTime;
  const time = new Date(seconds * 1000);
  const hours = String(time.getHours()).padStart(2, '0');
  const minutes = String(time.getMinutes()).padStart(2, '0');
  const secondsStr = String(time.getSeconds()).padStart(2, '0');
  return `${hours}:${minutes}:${secondsStr}`;
});
const currentTime = computed(() => {
  const seconds = satelliteValue.value + store.$state.startTime;
  const time = new Date(seconds * 1000);
  const year = time.getFullYear();
  const month = String(time.getMonth() + 1).padStart(2, '0');
  const day = String(time.getDate()).padStart(2, '0');
  const hours = String(time.getHours()).padStart(2, '0');
  const minutes = String(time.getMinutes()).padStart(2, '0');
  const secondsStr = String(time.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${secondsStr}`;
});


// 最大值为结束时间
const maxValue = computed(() => store.$state.endTime - store.$state.startTime);
// 计算刻度
const marks = computed(() => {
  const markObj = {};
  // 添加大刻度线（每2分钟）
  for (let time = store.$state.startTime; time <= store.$state.endTime; time += store.$state.interval) {
    markObj[time - store.$state.startTime] = {
      label: formatTime(time) == '00:00' ? formatTime(time, 'beforeDawn') : formatTime(time), // 格式化时间标签
    };
    // 在每个大刻度之间添加小刻度
    for (let smallTime = time + store.$state.interval / store.$state.smallInterval; smallTime < time + store.$state.interval; smallTime += store.$state.interval / store.$state.smallInterval) {
      if (smallTime <= store.$state.endTime) {
        markObj[smallTime - store.$state.startTime] = {
          label: '', // 小刻度没有标签
        };
      }
    }
    nextTick().then(() => {
      let marks_elements = document.getElementsByClassName('el-slider__stop')
      let marks_labels = document.getElementsByClassName('el-slider__marks-text')
      for (let i = 0; i < marks_elements.length; i++) {
        if (marks_labels[i].innerHTML == '') {
          marks_elements[i].style.bottom = '25%';
          marks_elements[i].style.height = '50%';
        } else {
          marks_elements[i].style.height = '100%';
        }
      }
    })
  }

  return markObj;
});

const updateMarksStyle = () => {
  nextTick().then(() => {
    const marks_elements = document.getElementsByClassName('el-slider__stop')
    const marks_labels = document.getElementsByClassName('el-slider__marks-text')
    const currentValue = satelliteValue.value + store.$state.startTime // 当前实际时间值

    for (let i = 0; i < marks_elements.length; i++) {
      // 从元素的 style.left 获取百分比值
      const leftPercentage = parseFloat(marks_elements[i].style.left)
      // 将百分比转换为实际时间值
      const totalDuration = store.$state.endTime - store.$state.startTime
      const markTime = store.$state.startTime + (totalDuration * leftPercentage / 100)
      
      // 设置刻度高度
      if (marks_labels[i]?.innerHTML === '') {
        marks_elements[i].style.bottom = '25%'
        marks_elements[i].style.height = '50%'
      } else {
        marks_elements[i].style.height = '100%'
      }
      
      // 设置刻度和文字颜色 - 只有当前进度之前的变白色
      if (markTime <= currentValue) {
        marks_elements[i].style.background = '#FFFFFF'
        if (marks_labels[i]) {
          marks_labels[i].style.color = '#FFFFFF'
        }
      } else {
        marks_elements[i].style.background = '#CCCCCC'
        if (marks_labels[i]) {
          marks_labels[i].style.color = '#CCCCCC'
        }
      }
    }
  })
}

// 修改 watch 监听器
watch(() => satelliteValue.value, (newVal) => {
  store.timeChange({
    time: (newVal + store.$state.startTime) * 1000,
    sateValue: newVal
  })
  updateMarksStyle()
}, { immediate: true })

// 格式化时间为 HH:mm 格式
const formatTime = (seconds, type) => {
  const date = new Date(seconds * 1000);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const secondsStr = String(date.getSeconds()).padStart(2, '0');
  if (type == 'beforeDawn') {
    return `${month}-${day}`;
  } else {
    return `${hours}:${minutes}`;
  }
};
// 计算开始时间和结束时间的显示格式
const formattedStartTime = computed(() => formatTime(startTime.value));
const formattedEndTime = computed(() => formatTime(store.$state.endTime));

// 滑块变化时的回调
const onSliderChange = (value) => {
};
onMounted(() => {
  updateMarksStyle()
})
</script>

<style lang="scss" scoped>
@forward './timeAxis';


// 下拉选择器css
:deep(.el-select) {
  width: 60px;
  height: 24px;
}

:deep(.el-input) {
  width: 60px;
  height: 24px;
  // border: none;
  font-size: 12px;
  --el-input-border-color: #5e83d4;
}

:deep(.el-select__caret) {
  color: #fff !important; //箭头颜色
}

:deep(.el-input__inner) {
  font-size: 12px;
  color: #fff;
}

:deep(.el-input__wrapper) {
  background: rgba(30, 85, 204, 0.64);
}

//时间滑块css
:deep(.el-slider) {
  //外框
  height: 32px;
  padding-top: 0;
}

// :deep(.el-slider__marks-text) {
//   color: #fff !important;
// }

:deep(.el-slider__runway) {
  //灰色底框
  height: 12px;
  border-radius: 0;
  margin: 0;
  // background: #a3bce2;
  background: rgba(163, 188, 226, 0.8);
}

:deep(.el-slider__bar) {
  //蓝色划过框
  height: 12px;
  border-radius: 0;
  margin: 0;
  background: rgba(30, 85, 204, 0.8);
}

:deep(.el-slider__button) {
  //按钮
  display: none;
}

/* 自定义刻度线的样式 */
:deep(.el-slider__stop) {
  position: absolute;
  bottom: 2%;
  height: 96%;
  width: 1px;
  border-radius: 0%;
  background: #CCCCCC;
  transition: background-color 0.3s ease;
}

:deep(.el-slider__marks-text) {
  font-size: 12px;
  color: #CCCCCC;
  transition: color 0.3s ease;
}

.nowTime {
  width: 70px;
  text-align: center;
  font-size: 12px;
  padding: 1px;
  transform: translateX(-50%);
  background-color: #fff;
  box-sizing: border-box;
  border-radius: 5px;
  display: block;

  &::after {
    content: '';
    position: absolute;
    width: 0;
    height: 0;
    border: 5px solid #fff;
    border-color: #fff transparent transparent transparent;
    bottom: -8px;
    left: 50%;
    transform: translateX(-55%);
  }
}
</style>
